var years = $("#years"),
    months = $("#months"),
    days = $("#days"),
    rate = $("#rate"),
    rewardRate = $("#rewardRate"),
    additionalRate = $("#additionalRate"),
    amount = $("#amount"),
    title = $("#title"),
    timeOut = $("#timeOut"),
    loginName = $("#loginName"),
    minAmount = $("#minAmount"),
    maxAmount = $("#maxAmount"),
    stepAmount = $("#stepAmount"),
    repayMethod = $("#repayMethod"),
    contractId = $("#contractId"),
    loanProduct = $("#loanProduct"),
    loanDirect = $("#loanDirect"),//是否定向
    //description = $("#description"),
    //guaranteeInfo = $("#guaranteeInfo"),
    //mortgageInfo = $("#mortgageInfo"),

    // 費率
    serviceFee = $("#serviceFee"),
    guaranteeFee = $("#guaranteeFee"),
    manageFee = $("#manageFee"),
    investFee = $("#investFee"),
    activityLink = $("#activityLink"),
    error_message = $("#error_message"),
    alertPanel = $(".alert"),
    page_url = decodeURI(location.href),
    start = page_url.indexOf("?");

// 预填借款人用户名
if (start !== -1) {
    loginName.val(page_url.substring(start + 1));
}
$("#loanProduct option[value='BANK']").remove();
$("#loanProduct option[value='BUSINESS']").remove();
// 初始化还款方式下拉列表
$('.multiselect').multiselect();

/**
 * 初始化富文本编辑器
 */
function initEditor() {
    var height = 150;
    $(".summernote").summernote({
        height: height, //set editable area's height
        focus: false, //set focus editable area after Initialize summernote
        lang: 'zh-CN',
        fontNames: [
            'Microsoft Yahei', 'Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
            'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande'
        ],
        toolbar: [
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['font', ['strikethrough', 'superscript', 'subscript']],
            ['fontsize', ['fontsize']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['codeview', ['codeview']],
            ['fullscreen', ['fullscreen']]
        ]
    });
}
//initEditor();

// 初始化标的信息
var currLoan;
var loanId = $("input[name=id]").val();
if (loanId && loanId !== '') {
    $.get("loan/getById/" + loanId, function (data) {
        if (data) {
            var loan = data.loan, fee = data.fee;
            title.val(loan.title);
            repayMethod.multiselect('select', loan.repayMethod);
            repayMethod.multiselect('refresh');
            loanProduct.multiselect('select', loan.loanProduct);
            loanProduct.multiselect('refresh');
            loanDirect.multiselect('select', loan.loanDirect);
            loanDirect.multiselect('refresh');
            contractId.multiselect('select', loan.contractId);
            contractId.multiselect('refresh');
            amount.val(loan.amount);
            rate.val(parseFloat(loan.rate / 100).toFixed(1));
            rewardRate.val(parseFloat(loan.rewardRate / 100).toFixed(1));
            if (loan.additionalRate) {
                additionalRate.val(parseFloat(loan.additionalRate / 100).toFixed(1));
            } else {
                additionalRate.val(0);
            }
            years.val(loan.duration.years);
            months.val(loan.duration.months);
            days.val(loan.duration.days);
            timeOut.val(loan.timeOut);
            //description.val(loan.description);

            // 创建标的之后，借款人即不可变更
            loginName.val(data.userLoginName).prop("disabled", true);
            
            // 投标规则
            minAmount.val(loan.investRule.minAmount);
            maxAmount.val(loan.investRule.maxAmount);
            stepAmount.val(loan.investRule.stepAmount);
            // 标的费率
            serviceFee.val(parseFloat(fee.serviceFee * 100).toFixed(2));
            guaranteeFee.val(parseFloat(fee.guaranteeFee * 100).toFixed(2));
            manageFee.val(parseFloat(fee.manageFee * 100).toFixed(2));
            investFee.val(parseFloat(fee.investFee * 100).toFixed(2));
            activityLink.val(loan.activityLink);

            // 避免天标被编辑为非一次性还本付息
            checkDay();
            $('button.multiselect:eq(2)').prop("disabled", true);
            console.log(loan.status);
            switch(loan.status) {
                case "PROPOSED":
                case "REJECTED":
                case "APPROVED":
                    break;
                case "SCHEDULED":
                    // repayMethod
                    $('button.multiselect:first').prop("disabled", true);
                    amount.prop("disabled", true);
                    rate.prop("disabled", true);
                    additionalRate.prop("disabled", true);
                    years.prop("disabled", true);
                    months.prop("disabled", true);
                    days.prop("disabled", true);
                    timeOut.prop("disabled", true);
                    serviceFee.prop("disabled", true);
                    guaranteeFee.prop("disabled", true);
                    manageFee.prop("disabled", true);
                    investFee.prop("disabled", true);
                    break;
                case "OPEN":
                case "CANCELED":
                case "ARCHIVED":
                    // repayMethod
                    $('button.multiselect:first').prop("disabled", true);
                    // loanProduct
                    $('button.multiselect:eq(1)').prop("disabled", true);
                    amount.prop("disabled", true);
                    rate.prop("disabled", true);
                    additionalRate.prop("disabled", true);
                    years.prop("disabled", true);
                    months.prop("disabled", true);
                    days.prop("disabled", true);
                    timeOut.prop("disabled", true);
                    serviceFee.prop("disabled", true);
                    guaranteeFee.prop("disabled", true);
                    manageFee.prop("disabled", true);
                    investFee.prop("disabled", true);
                    minAmount.prop("disabled", true);
                    maxAmount.prop("disabled", true);
                    stepAmount.prop("disabled", true);
                    break;
                case "FAILED":
                case "FINISHED":
                case "LOANED":
                case "CLEARED":
                case "OVERDUE":
                    // repayMethod
                    $('button.multiselect:first').prop("disabled", true);
                    // loanProduct
                    $('button.multiselect:eq(1)').prop("disabled", true);
                    amount.prop("disabled", true);
                    rate.prop("disabled", true);
                    additionalRate.prop("disabled", true);
                    years.prop("disabled", true);
                    months.prop("disabled", true);
                    days.prop("disabled", true);
                    timeOut.prop("disabled", true);
                    serviceFee.prop("disabled", true);
                    guaranteeFee.prop("disabled", true);
                    manageFee.prop("disabled", true);
                    investFee.prop("disabled", true);
                    minAmount.prop("disabled", true);
                    maxAmount.prop("disabled", true);
                    stepAmount.prop("disabled", true);
                    title.prop("disabled", true);
                    break;
            }
            currLoan = loan;
        }
    });
} else {
    $.get("loan/getDefaultLoanFee", function (fee) {
        if (fee) {
            serviceFee.val(parseFloat(fee.serviceFee * 100).toFixed(2));
            guaranteeFee.val(parseFloat(fee.guaranteeFee * 100).toFixed(2));
            manageFee.val(parseFloat(fee.manageFee * 100).toFixed(2));
            investFee.val(parseFloat(fee.investFee * 100).toFixed(2));
        }
    });
}

function showError(msg) {
    error_message.text(msg);
    alertPanel.show();
}
function hideError() {
    error_message.text('');
    alertPanel.hide();
}
/**
 * 验证借款金额
 * @returns {Boolean}
 */
function checkAmount() {
    var raw = amount.val(), value = parseInt(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("金额格式不正确");
        amount.val('');
        return false;
    }
    return true;
}
amount.on("change", checkAmount);
/**
 * 验证年化利率
 * @returns {Boolean}
 */
function checkRate() {
    var raw = rate.val(), value = parseFloat(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("利率格式不正确");
        rate.val('');
        return false;
    } else if (value * 100 < sysMinLoanRate || value * 100 > sysMaxLoanRate) {
        showError("利率必须在 " + sysMinLoanRate / 100 + "% - " + sysMaxLoanRate / 100 + "% 之间");
        rate.val('');
        return false;
    }
    return true;
}
rate.on("change", checkRate);
/**
 * 验证附加费率
 * @returns {Boolean}
 */
function checkAddRate() {
    var raw = additionalRate.val(), value = parseFloat(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value < 0) {
        showError("附加利率格式不正确");
        additionalRate.val('');
        return false;
    }
    return true;
}
additionalRate.on("change", checkRate);
/**
 * 验证借款期限年
 * @returns {Boolean}
 */
function checkYear() {
    var raw = years.val(), value = parseInt(raw);
    if (isNaN(value) || value != raw || value < 0) {
        years.val(0);
        return false;
    } else if (value !== 0) {
        days.val(0);
        $('button.multiselect:first').prop("disabled", false);
    }
    return true;
}
years.on("change", checkYear);
/**
 * 验证借款期限月
 * @returns {Boolean}
 */
function checkMonth() {
    var raw = months.val(), value = parseInt(raw);
    if (isNaN(value) || value != raw || value < 0 || value > 12) {
        months.val(0);
        return false;
    } else if (value !== 0) {
        days.val(0);
        $('button.multiselect:first').prop("disabled", false);
    }
    return true;
}
months.on("change", checkMonth);
/**
 * 验证借款期限日
 * @returns {Boolean}
 */
function checkDay() {
    var raw = days.val(), value = parseInt(raw);
    if (isNaN(value) || value != raw || value < 0) {
        days.val(0);
        return false;
    } else if (value !== 0) {
        years.val(0);
        months.val(0);
        // 天标只能使用一次性还本付息
        $('#repayMethod').multiselect('select', 'BULLET_REPAYMENT');
        $('button.multiselect:first').prop("disabled", true);
    }
    return true;
}
days.on("change", checkDay);
/**
 * 检验借款期限
 * @returns {undefined}
 */
function checkDuration() {
    if (years.val() == 0 && months.val() == 0 && days.val() == 0) {
        showError("请输入借款周期");
        return false;
    }
    return true;
}
/**
 * 检验筹款时长
 * @returns {undefined}
 */
function checkTimeOut() {
    var raw = timeOut.val(), value = parseInt(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("筹款时长输入有误");
        timeOut.val('');
        return false;
    }
    return true;
}
timeOut.on("change", checkTimeOut);


function checkMinAmount() {
    var raw = minAmount.val(), value = parseInt(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("最小投标金额格式不正确");
        minAmount.val('');
        return false;
    }
    return true;
}
minAmount.on("change", checkMinAmount);

function checkMaxAmount() {
    var raw = maxAmount.val(), value = parseInt(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("最大投标金额格式不正确");
        maxAmount.val('');
        return false;
    }
    return true;
}
maxAmount.on("change", checkMaxAmount);

function checkStepAmount() {
    var raw = stepAmount.val(), value = parseInt(raw);
    if (raw === '')
        return false;
    if (isNaN(value) || value != raw || value < 0) {
        showError("投标金额增量格式不正确");
        stepAmount.val('');
        return false;
    }
    return true;
}
stepAmount.on("change", checkStepAmount);


$("input[type=text]").focus(function () {
    hideError();
});

var saveLoanBtn = $("#saveLoanBtn");
/**
 * 提交表单
 * 
 * @param {type} param
 */
saveLoanBtn.click(function () {
    // 检验标的名称
    if (title.val() === '') {
        showError("请输入标的名称");
        return;
    }
    // 检验标的金额
    if (amount.val() === '') {
        showError("请输入标的金额");
        return;
    } else if (!checkAmount())
        return;
    // 检验年化利率
    if (rate.val() === '') {
        showError("请输入年化利率");
        return;
    } else if (!checkRate())
        return;
    // 检验附加利率
    if (additionalRate.val() === '') {
        showError("请输入附加利率");
        return;
    } else if (!checkAddRate())
        return;
    // 检验标的借款周期
    if (!checkDuration())
        return;
    // 检验筹款时长
    if (timeOut.val() === '') {
        showError("请输入筹款时长");
        return;
    } else if (!checkTimeOut())
        return;

    // 检验最小投标金额
    if (minAmount.val() === '') {
        showError("请输入最小投标金额");
        return;
    } else if (!checkMinAmount())
        return;
    // 检验最小投标金额
    if (maxAmount.val() === '') {
        showError("请输入最大投标金额");
        return;
    } else if (!checkMaxAmount())
        return;
    // 检验最小投标金额
    if (stepAmount.val() === '') {
        showError("请输入投标金额增量");
        return;
    } else if (!checkStepAmount())
        return;

    if (parseInt(minAmount.val()) > parseInt(maxAmount.val())) {
        showError("最小投标金额不可大于最大投标金额");
        return;
    }

    // 检验借款人用户名
    if (loginName.val() === '') {
        showError("请输入借款人用户登录名或手机号");
        return;
    } else {
        $.get("user/canLoan/" + loginName.val(), function (res) {
            if (!res.success) {
                showError(res.message);
                return;
            } else {
                // 保存标的信息
                var data = sys.formToJson($("#loanForm"));
                data.rate = data.rate * 100;
                data.rewardRate = data.rewardRate * 100;
                data.additionalRate = data.additionalRate * 100;
                data.userId = res.message;
                // 费率由百分数调整为小数
                data.serviceFee = data.serviceFee / 100;
                data.guaranteeFee = data.guaranteeFee / 100;
                data.manageFee = data.manageFee / 100;
                data.investFee = data.investFee / 100;
                sys.btnSpin(saveLoanBtn);
                $.post("loan/save", data, function (result) {
                    if (result.success) {
                        if (currLoan) {
                            sys.alert(result.message, function () {
                                location.href = "loan/list/" + currLoan.status.toLowerCase();
                            });
                        } else {
                            sys.alert(result.message, function () {
                                location.href = "loan/list/proposed";
                            });
                        }
                    } else {
                        sys.alert(result.message);
                    }
                }).fail(function () {
                    alert("服务器错误");
                });
            }
        });
    }
});
